package com.aba.im.pojo;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ClientMain {
    private JFrame userFrame;
    private JFrame chatFrame;
    private JTextField userInputField;
    private JTextArea chatArea;
    private Socket socket;
    private BufferedReader in;
    private PrintWriter out;
    private String username;
    private SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm"); // 时间格式
    
    public ClientMain() {
        try {
            socket = new Socket("localhost", 12345);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);

            // 用户窗口
            userFrame = new JFrame("User Interface");
            userFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            userFrame.setSize(300, 200);
            userFrame.setLayout(new BorderLayout());

            JLabel usernameLabel = new JLabel("Enter your username:");
            userFrame.add(usernameLabel, BorderLayout.NORTH);

            userInputField = new JTextField();
            userFrame.add(userInputField, BorderLayout.CENTER);

            JButton loginButton = new JButton("Login");
            loginButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    username = userInputField.getText();
                    if (!username.isEmpty()) {
                        out.println(username);
                        userFrame.setVisible(false);
                        initChatFrame();
                    }
                }
            });
            userFrame.add(loginButton, BorderLayout.SOUTH);
            userFrame.setVisible(true);

            new Thread(() -> {
                try {
                    String message;
                    while ((message = in.readLine()) != null) {
                        // 接收服务端消息时添加当前时间戳
                        updateChatArea(message, timeFormat.format(new Date()));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void initChatFrame() {
        chatFrame = new JFrame("Group Chat");
        chatFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        chatFrame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                if (JOptionPane.showConfirmDialog(chatFrame,
                        "确定退出群聊？", "退出确认",
                        JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                    logout(); // 封装退出逻辑
                }
            }
        });
        chatFrame.setSize(450, 500);
        chatFrame.setLayout(new BorderLayout());
        
        // 聊天显示区域优化
        chatArea = new JTextArea();
        chatArea.setEditable(false);
        chatArea.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14)); // 优化字体
        JScrollPane scrollPane = new JScrollPane(chatArea);
        chatFrame.add(scrollPane, BorderLayout.CENTER);
        
        // 输入面板增强
        JPanel inputPanel = new JPanel(new BorderLayout(5, 0)); // 添加内边距
        inputPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); // 外边框留白
        
        // 输入框提示语实现
        JTextField inputField = new JTextField("输入消息...");
        inputField.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        inputField.addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent e) {
                if (inputField.getText().equals("输入消息...")) {
                    inputField.setText("");
                }
            }
            @Override
            public void focusLost(FocusEvent e) {
                if (inputField.getText().isEmpty()) {
                    inputField.setText("输入消息...");
                }
            }
        });
        inputField.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String message = inputField.getText();
                if (!message.trim().isEmpty()) {
                    sendMessage(message);
                    inputField.setText("");
                }
            }
        });
        inputPanel.add(inputField, BorderLayout.CENTER);
        
        // 功能按钮区（表情/文件/退出）
        JPanel functionPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 0));
        JButton emojiBtn = new JButton("😀");
        emojiBtn.setPreferredSize(new Dimension(30, 30));
        JButton fileBtn = new JButton("📎");
        fileBtn.setPreferredSize(new Dimension(30, 30));
        JButton exitBtn = new JButton("退出");
        exitBtn.addActionListener(e -> logout());
        
        functionPanel.add(emojiBtn);
        functionPanel.add(fileBtn);
        functionPanel.add(exitBtn);
        inputPanel.add(functionPanel, BorderLayout.EAST);
        
        chatFrame.add(inputPanel, BorderLayout.SOUTH);
        chatFrame.setVisible(true);
    }
    
 // 发送消息（带时间戳）
    private void sendMessage(String message) {
        out.println(message);
        if ("/exit".equals(message)) {
            logout();
        } else {
            String time = timeFormat.format(new Date());
            updateChatArea(message, time); // 发送方消息添加时间
        }
    }
    
    // 退出登录逻辑封装
    private void logout() {
        out.println("/exit");
        try {
            if (socket != null && !socket.isClosed()) {
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.exit(0);
    }
    
 // 更新聊天区域（增加时间参数）
    private void updateChatArea(String message, String time) {
        String formattedMsg;
        if (message.startsWith("[系统]")) {
            // 系统消息样式
            formattedMsg = message + " [" + time + "]";
        } else if (message.contains(" joined the chat") || message.contains(" left the chat")) {
            // 成员加入/退出提示
            formattedMsg = "[系统] " + message + " [" + time + "]";
        } else {
            // 普通消息（用户名加粗）
            formattedMsg = "[ " + username + " ] " + time + " > " + message;
        }
        chatArea.append(formattedMsg + "\n");
        chatArea.setCaretPosition(chatArea.getDocument().getLength());
    }
    
    public static void main(String[] args) {
        new ClientMain();
    }
}